package org.lzy.shop.base

import ExceptionHandler
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import org.lzy.shop.interfaces.IApiErrorCallback
import org.lzy.shop.network.ApiException
import org.lzy.shop.network.ERROR
import org.lzy.shop.network.NetworkStateManager
import org.lzy.shop.util.ErrorHandler

abstract class BaseViewModel : ViewModel() {

    // 添加错误消息LiveData
    val errorMessage = MutableLiveData<String?>()

    protected val networkStateObserver = object : NetworkStateManager.NetworkStateListener {
        override fun onNetworkStateChanged(isAvailable: Boolean) {
            // 可以在这里处理网络状态变化，比如显示提示信息
            if (isAvailable) {
                // 网络恢复，可以尝试重新请求失败的网络操作
            } else {
                // 网络断开
            }
        }
    }

    /**
     * 运行在主线程中，可直接调用
     * @param errorBlock 错误回调
     * @param responseBlock 请求函数
     */
    fun launchUI(errorBlock: (Int?, String?) -> Unit, responseBlock: suspend () -> Unit) {
        viewModelScope.launch(Dispatchers.Main) {
            safeApiCall(errorBlock = errorBlock, responseBlock)
        }
    }

    /**
     * 需要运行在协程作用域中
     * @param errorBlock 错误回调
     * @param responseBlock 请求函数
     */
    suspend fun <T> safeApiCall(
        errorBlock: suspend (Int?, String?) -> Unit,
        responseBlock: suspend () -> T?
    ): T? {
        try {
            return responseBlock()
        } catch (e: Exception) {
            val exception = ExceptionHandler.handleException(e)
            errorBlock(exception.errCode, exception.errMsg)

        }
        return null
    }

    /**
     * 不依赖BaseRepository，运行在主线程中，可直接调用
     * @param errorCall 错误回调
     * @param responseBlock 请求函数
     * @param successBlock 请求回调
     */
    fun <T> launchUIWithResult(
        responseBlock: suspend () -> BaseResponse<T>?,
        errorCall: IApiErrorCallback?,
        successBlock: (T?) -> Unit
    ) {
        viewModelScope.launch(Dispatchers.Main) {
            val result = safeApiCallWithResult(errorCall = errorCall, responseBlock)
            successBlock(result)
        }
    }

    /**
     * 不依赖BaseRepository，需要在作用域中运行
     * @param errorCall 错误回调
     * @param responseBlock 请求函数
     */
    suspend fun <T> safeApiCallWithResult(
        errorCall: IApiErrorCallback?,
        responseBlock: suspend () -> BaseResponse<T>?
    ): T? {
        try {
            //将主线程从当前线程脱离然后切到IO线程，执行完成后自动切回主线程
            val response = withContext(Dispatchers.IO) {
                withTimeout(10000) {
                    responseBlock()
                }
            } ?: return null

            if (response.isFailed()) {
                throw ApiException(response.code, response.message)
            }
            return response.data
        } catch (e: Exception) {
            e.printStackTrace()
            val exception = ExceptionHandler.handleException(e)
            if (ERROR.UNLOGIN.code == exception.errCode) {
                errorCall?.onFail(exception.errCode, exception.errMsg)
            } else {
                errorCall?.onError(exception.errCode, exception.errMsg)
            }
        }
        return null
    }

    init {
        // 注册网络状态监听器
        NetworkStateManager.registerListener(networkStateObserver)
    }

    // 在ViewModel的onCleared方法中取消注册
    override fun onCleared() {
        super.onCleared()
        NetworkStateManager.unregisterListener(networkStateObserver)
    }



    /**
     * 安全的API调用
     */
    protected suspend fun <T> safeApiCall(
        errorCall: IApiErrorCallback?,
        responseBlock: suspend () -> T?
    ): T? {
        val response: T? = try {
            // 检查网络连接状态
            if (!NetworkStateManager.isNetworkAvailable) {
                throw ApiException(ERROR.NETWORD_ERROR.code, ERROR.NETWORD_ERROR.errMsg)
            }

            // 执行网络请求
            withTimeout(10000) { // 添加超时处理
                responseBlock()
            }
        } catch (e: Exception) {
            // 处理异常
            val apiException = if (e is ApiException) e else ErrorHandler.handleException(e)

            // 通知错误回调
            errorCall?.onError(apiException.errCode, apiException.errMsg)

            // 发送错误消息
            errorMessage.value = apiException.errMsg

            null
        }

        return response
    }
}